import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const login = (userToken, userData) => {
    token.value = userToken
    userInfo.value = userData
    localStorage.setItem('token', userToken)
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
  }

  // 设置用户信息
  const setUserInfo = data => {
    userInfo.value = data
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      // 这里可以调用获取用户信息的API
      // const res = await getUserInfo()
      // setUserInfo(res.data)
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    setUserInfo,
    fetchUserInfo,
  }
})
